﻿using System;
using System.Globalization;
using Microsoft.SharePoint;

namespace SPRepository
{
    public class SingleLookupFieldType : SimpleFieldType<LookupFieldDto>
    {
        public SingleLookupFieldType(Guid id) : base(id)
        {
        }

        public override LookupFieldDto GetValue(SPListItem item)
        {
            var fieldValue = GetFieldValue<SPFieldLookupValue>(item);
            if (fieldValue == null)
            {
                return null;
            }
            var dto = new LookupFieldDto(fieldValue.LookupId, fieldValue.LookupValue);
            return dto;
        }

        public override void SetValue(SPListItem item, LookupFieldDto value)
        {
            SPFieldLookupValue fieldValue;
            if (value != null)
            {
                fieldValue = new SPFieldLookupValue(value.LookupId.ToString(CultureInfo.InvariantCulture));
            }
            else
            {
                fieldValue = new SPFieldLookupValue();
            }
            item[FieldId] = fieldValue;
        }
    }
}